import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入 nprogress
import nprogress from 'nprogress'

// 导入登陆组件
// @ 符号代表 src 文件夹,是vue本身提供的快捷方式
// 导入登录组件
import Login from '@/components/Login.vue'
// 导入 Home 组件
import Home from '@/components/Home.vue'
// 导入 Welcome 组件
import Welcome from '@/components/Welcome.vue'
// 导入用户列表组件
import Users from '@/components/User/Users.vue'
// 导入权限列表组件
import Rights from '@/components/Power/Rights.vue'
// 导入角色列表组件
import Roles from '@/components/Power/Roles.vue'
// 导入商品分类组件
import Category from '@/components/Goods/Cate.vue'
// 导入分类参数组件
import Params from '@/components/Goods/Params.vue'
// 导入商品列表组件
import Goods from '@/components/Goods/Goods.vue'
// 导入添加商品组件
import GoodAdd from '@/components/Goods/GoodAdd.vue'
// 导入订单管理组件
import Order from '@/components/Order/Order.vue'
// 导入数据统计组件
import Reports from '@/components/Reports/Reports.vue'

Vue.use(VueRouter)

// 配置路由规则
const routes = [
  // 重定向
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Category },
      { path: '/params', component: Params },
      { path: '/goods', component: Goods },
      { path: '/good/addgood', component: GoodAdd },
      { path: '/orders', component: Order },
      { path: '/reports', component: Reports }
    ]
  }
]

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

// 导航守卫,也叫路由守卫
// 作用: 就是对路由进行拦截,然后根据场景对路由进行处理
// 例如: 登录判断有没有对应的 token 值
router.beforeEach((to, from, next) => {
  nprogress.start()
  // to -- 即将进入的路由
  // from -- 即将离开的路由
  // next -- 是一个函数,决定是否进入下一步操作
  //         next() 放行   next('/xxx') 强行跳转到 xxx 路由
  if (to.path === '/login') return next()
  // 将本地的 token 值取出
  var tokenStr = window.sessionStorage.getItem('token')
  // 判断是否有 token 值
  if (!tokenStr) return next('/login')
  next()
})

router.afterEach((to, from) => {
  nprogress.done()
})

export default router
